package com.breaking.second.activity.pager.news;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson2.JSONObject;
import com.breaking.second.R;
import com.breaking.second.activity.pager.BaseFragment;
import com.breaking.second.activity.pager.adapter.NewsAdapter;
import com.breaking.second.application.EscortApplication;
import com.breaking.second.databinding.DialogNewsBinding;
import com.breaking.second.databinding.PagerNewsBinding;
import com.breaking.second.entity.BookEntity;
import com.breaking.second.entity.NewsEntity;
import com.breaking.second.entity.UserLoginEntity;
import com.breaking.second.utils.StringUtil;
import com.breaking.second.utils.compat.DialogCompat;
import com.breaking.second.utils.compat.RefreshLayoutCompat;
import com.breaking.second.utils.compat.SkeltonCompat;
import com.breaking.second.utils.okhttp.OkhttpUtil;
import com.ethanhua.skeleton.ViewSkeletonScreen;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;

//消息列表
public class NewsPager extends BaseFragment<PagerNewsBinding> {
    private final List<NewsEntity> newsEntities = new ArrayList<>();
    private NewsAdapter newsAdapter;
    private ViewSkeletonScreen d;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initSmart();
        initRecycler();
        initData();
        initView();
        initSkelton();
    }

    private void initView() {
        binding.toolbar.setOnMenuItemClickListener(this::OnMenuItemClick);
    }

    private boolean OnMenuItemClick(MenuItem menuItem) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        DialogNewsBinding newsBinding = DialogNewsBinding.inflate(getLayoutInflater());
        builder.setView(newsBinding.getRoot());
        builder.setPositiveButton("发送", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Editable user_id = newsBinding.userId.getText();
                Editable message = newsBinding.message.getText();
                if (StringUtil.isEmpty(user_id)) {
                    Toast.makeText(requireActivity(), "账号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                } else if (StringUtil.isEmpty(message)) {
                    Toast.makeText(requireActivity(), "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                addChat(user_id.toString(), message.toString());
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        AlertDialog alertDialog = builder.show();
        DialogCompat.init(alertDialog.getWindow());
        return true;
    }

    private void addChat(String user_id, String message) {
        JSONObject form = new JSONObject();
        form.put("content", message.toString());
        form.put("toUserId", user_id.toString());
        form.put("userId", String.valueOf(pageableVo.getUserId()));
        OkhttpUtil.Post("chat", form, new OkhttpUtil.CallbackListener(this::addChat));
    }

    private void addChat(BookEntity bookEntity) {
        if (bookEntity.isCode()) {
            getNewsData();
        }
        Toast.makeText(requireActivity(), bookEntity.getMsg(), Toast.LENGTH_SHORT).show();
    }

    private void initSkelton() {
        d = SkeltonCompat.bind(binding.smart, R.layout.layout_empty).show();
    }

    private void initData() {
        getNewsData();
    }

    private void getNewsData() {
        FormBody.Builder builder = new FormBody.Builder();
        UserLoginEntity userLoginEntity = EscortApplication.getUserLoginEntity();
        if (userLoginEntity != null) {
            builder.add("userId", String.valueOf(userLoginEntity.getId()));
        }
        OkhttpUtil.Get("chat/user", builder, new OkhttpUtil.CallbackListener(this::getNewsData));
    }

    private void getNewsData(BookEntity bookEntity) {
        if (bookEntity.isCode()) {
            List<NewsEntity> newsEntityList = bookEntity.toList(NewsEntity.class);
            if (newsEntityList == null) return;
            if (newsEntityList.isEmpty()) return;
            if (pageableVo.getCurrent() == 0) {
                newsAdapter.notifyItemRangeRemoved(0, this.newsEntities.size() + 1);
                this.newsEntities.clear();
            }
            this.newsEntities.addAll(newsEntityList);
            newsAdapter.notifyItemRangeChanged(0, this.newsEntities.size());
            if (!this.newsEntities.isEmpty()) {
                d.hide();
            }
        }
    }

    private void initRecycler() {
        newsAdapter = new NewsAdapter(requireContext(), newsEntities);
        binding.recycler.setLayoutManager(new LinearLayoutManager(requireContext()));
        binding.recycler.setAdapter(newsAdapter);
    }

    private void initSmart() {
        RefreshLayoutCompat.setRefresh(pageableVo, binding.smart, this::OnRefresh);
    }

    private void OnRefresh(RefreshLayout refreshLayout) {
        getNewsData();
    }

}
